package com.mgq.juc.reentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author MaGuangQi
 * 演示tryLock() 超时
 * @date 2021-12-17 09:27
 **/
@Slf4j
public class TestTryLock {
    private  static  ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            //if (!lock.tryLock()) {
            try {
                if (!lock.tryLock(3, TimeUnit.SECONDS)) {
                    log.debug("没有获得到锁");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("获取不到锁,被打断了");
                return;
            }
            try {
                log.debug("获取到锁");
            } finally {
                lock.unlock();
            }

        }, "t1");

        t1.start();
        lock.lock();
        log.debug("主线程锁住对象");
        Thread.sleep(1000);
        t1.interrupt();
        log.debug("打断t1");

    }
}
